﻿using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Net;
using System.Collections.Generic;

public class Login : MonoBehaviour {

    private string IPSTR = "IPSTR";
    private string NAMESTR = "NAMESTR";
    public Text ipText;
    public InputField m_inputIp;
    public InputField m_inputUSerName;

    public Text m_txtMessage;

    public GameWindow gameWindow;

    private bool m_beLogined = false;
    private bool m_beServerReject = false;
	// Use this for initialization
	void Awake () 
    {
        Screen.SetResolution(480, 720, false);
        NetHelper.RegisterEvent(MessageName.Login, OnLogin);
        NetHelper.RegisterEvent(MessageName.LoginResult, OnLoginResult);
        m_inputIp.text = LoadIPInfo();
        m_inputUSerName.text = LoadUserName();
        ipText.text = GetAddressIP();
	}

    
	
	// Update is called once per frame
	void Update () 
    {
	    
	}

    public void SetShow(bool beShow)
    {
        gameWindow.gameObject.SetActive(!beShow);
        gameObject.SetActive(beShow);
        if (!beShow)
        {
            m_beLogined = true;
        }
        else
        {
            m_beLogined = false;
        }
    }

    public void GameLogin()
    {
        string ip = m_inputIp.text;
        string userName = m_inputUSerName.text;

        if (!IsIpAddress(ip))
        {
            this.m_txtMessage.text = "非法 IP";
            return;
        }

        SaveIPInfo(ip);
        SaveUserName(userName);

        NetHelper.Connect(ip, 2048, OnConnectResult);
        m_beServerReject = false;
        StartCoroutine(InWaitTimeOut());
    }

    IEnumerator InWaitTimeOut()
    {
        yield return new WaitForSeconds(1f);
        if (!m_beLogined && !m_beServerReject)
        {
            this.m_txtMessage.text = "连接服务器失败";
        }
    }

    void OnConnectResult(bool beSuccess, string message)
    {
        if (beSuccess)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic["route"] = MessageName.Login;
            dic["name"] = m_inputUSerName.text;
            dic["coin"] = 0;

            NetHelper.Send(MessageName.Login, dic);
            
        }
        else
        {
            if (m_beLogined)
            {
                SetShow(true);
            }
            this.m_txtMessage.text = "连接服务器失败";
        }
    }

    private void OnLoginResult(Dictionary<string, object> message)
    {
        bool beSuccess = DictionaryUnity.GetSafeBoolValue(message, "besuccess");
        if (beSuccess)
        {
            
            string data = DictionaryUnity.GetSafeStringValue(message, "data");
            Debug.Log(data);
            FruitDataManager.Intstance.InitDate(data);
            SetShow(false);
        }
        else
        {
            m_beServerReject = true;
            this.m_txtMessage.text = "服务器拒绝连接";
        }
    }

    private void OnLogin(Dictionary<string, object> message)
    {
        Debug.Log(Json.Serialize(message));
    }


    private string LoadIPInfo()
    {
        return PlayerPrefs.GetString(IPSTR, "127.0.0.1");
    }
    private string LoadUserName()
    {
        return PlayerPrefs.GetString(NAMESTR, Dns.GetHostName());
    }

    private void SaveIPInfo(string ip)
    {
        PlayerPrefs.SetString(IPSTR, ip);
    }

    private void SaveUserName(string userName)
    {
        PlayerPrefs.SetString(NAMESTR, userName);
    }

    private bool IsIpAddress(string ipStr)
    {
        ipStr = ipStr.Trim();
        IPAddress ip;
        if (IPAddress.TryParse(ipStr, out ip))
        {
            return true;
        }
        return false;
    }

    /// <summary>
    /// 获取本地IP地址信息
    /// </summary>
    string GetAddressIP()
    {
        ///获取本地的IP地址
        string addressIP = string.Empty;
        foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
        {
            if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
            {
                addressIP = _IPAddress.ToString();
            }
        }
        return addressIP;
    }

    void OnDestroy()
    {
        NetHelper.RemoveAllEvent();
    }
}
